package hhm.android.account

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.alibaba.android.arouter.launcher.ARouter
import com.igexin.sdk.PushManager
import com.trello.rxlifecycle4.RxLifecycle
import com.trello.rxlifecycle4.android.ActivityEvent
import hhm.android.account.databinding.ActivityLibraryTwoBinding
import hhm.android.library.datePicker.bean.DateParams
import hhm.android.library.utils.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
import siau.android.base.*
import siau.android.http.model.CreateFamilyRequest
import siau.android.library.FileUtil
import siau.android.library.KeyString
import java.text.SimpleDateFormat
import java.util.*

class CreateLibraryTwoActivity : SBBaseActivity(), CoroutineScope by MainScope() {

    lateinit var viewModel: CreateLibraryTwoViewModel
    lateinit var dataBinding: ActivityLibraryTwoBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTitleWhiteAndTextBlank()
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_library_two)
        initTitle()
        viewModel = ViewModelProvider(this).get(CreateLibraryTwoViewModel::class.java)
        dataBinding.viewModel = viewModel
        dataBinding.lifecycleOwner = this

        val startActivityForResult = registerForActivityResult(IntentIntActivityResultContact()) {
            if (it == 1024) {
                setResult(1024)
                finish()
            }
        }

        viewModel.babyBirthday.observe(this, {
            dataBinding.activityLibraryTwoSelectBirthday.text = it
        })
        viewModel.babyIcon.observe(this, {
            GlideUtils.loadCircleImageNoCache(
                this, it, dataBinding.activityLibraryTwoIcon, R.mipmap.take_picture, R.mipmap.take_picture
            )
        })

        viewModel.babySex.observe(this, {
            when (it) {
                viewModel.sexBoy -> {
                    dataBinding.activityLibraryTwoBoyIv.setImageResource(R.mipmap.sex_boy_select)
                    dataBinding.activityLibraryTwoGirlIv.setImageResource(R.mipmap.sex_girl)
                }
                viewModel.sexGirl -> {
                    dataBinding.activityLibraryTwoBoyIv.setImageResource(R.mipmap.sex_boy)
                    dataBinding.activityLibraryTwoGirlIv.setImageResource(R.mipmap.sex_girl_select)
                }
                else -> {
                    dataBinding.activityLibraryTwoBoyIv.setImageResource(R.mipmap.sex_boy)
                    dataBinding.activityLibraryTwoGirlIv.setImageResource(R.mipmap.sex_girl)
                }
            }
        })

        viewModel.canNext.observe(this, {
            if (it) {
                dataBinding.activityLibraryTwoBtn.background = ContextCompat.getDrawable(this, R.drawable.rectangle_circle_maincolor)
            } else {
                dataBinding.activityLibraryTwoBtn.background = ContextCompat.getDrawable(this, R.drawable.rectangle_circle_grey_e6)
            }
        })

        dataBinding.activityLibraryTwoEt.addTextChangedListener(onTextChanged = { _, _, _, _ ->
            viewModel.babyName.value = dataBinding.activityLibraryTwoEt.text.toString()
            viewModel.canClick()
        })

        dataBinding.activityLibraryTwoSelectBirthday.setOnClickListener {
            DialogUtils.showDatePicBottomView(
                this,
                object : GetDateListener {
                    override fun getDate(date: Date, string: String) {
                        viewModel.babyBirthday.value = string
                        viewModel.canClick()
                    }
                },
                "yyyy/MM/dd",
                DateParams.TYPE_YEAR, DateParams.TYPE_MONTH, DateParams.TYPE_DAY,
            )
        }

        dataBinding.activityLibraryTwoBtn.setOnClickListener(object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                if (viewModel.canNext.value == true) {
                    val identityType = intent.getIntExtra(KeyString.identityType, 0)
                    val userIdentity = intent.getStringExtra(KeyString.userIdentity)
                    val i = Intent(this@CreateLibraryTwoActivity, CreateLibraryThreeActivity::class.java)
                    i.putExtra(KeyString.nickName, viewModel.babyName.value)
                    val sdf = SimpleDateFormat("yyyy/MM/dd")
                    val date = sdf.parse(viewModel.babyBirthday.value).time
                    i.putExtra(KeyString.birthday, date)
                    i.putExtra(KeyString.sex, viewModel.babySex.value)
                    i.putExtra(KeyString.avatar, viewModel.babyIcon.value)
                    i.putExtra(KeyString.identityType, identityType)
                    i.putExtra(KeyString.userIdentity, userIdentity)
                    startActivityForResult.launch(i)
                }
            }
        })

        val takePhotoResult = registerForActivityResult(TakePhotoActivityResultContact()) {
            if (it.resultCode != RESULT_OK) {
                return@registerForActivityResult
            }
            if (!TextUtils.isEmpty(TakePhotoPopWindowUtils.mTempPhotoPath)) {
                showLoadingDialog()
                //将图片显示在ivImage上
                HttpHelper().getQiNiuInfo()?.subscribe({ authTokenResponse ->
                    SBApplication.uploadManager.put(TakePhotoPopWindowUtils.mTempPhotoPath, "android" + Date().time + ".jpg", authTokenResponse.authToken, { key, info, res ->
                        TakePhotoPopWindowUtils.mTempPhotoPath = ""
                        //res 包含 hash、key 等信息，具体字段取决于上传策略的设置
                        if (info.isOK) {

                            hideLoadingDialog()
                            viewModel.babyIcon.value = authTokenResponse.domain + key
                            viewModel.canClick()

                        } else {
                            hideLoadingDialog()
                        }
                    }, null)

                }, { throwable ->
                    hideLoadingDialog()
                    showToast(throwable.message)
                })
            }
        }
        val selectPicResult = registerForActivityResult(TakePhotoActivityResultContact()) {


            if (it.intent == null || it.intent!!.data == null) {
                return@registerForActivityResult
            }
            showLoadingDialog()
            val uri: Uri = it.intent?.data!!
            val filePath: String = FileUtil.getFilePathByUri(this, uri)

            if (!TextUtils.isEmpty(filePath)) {
                HttpHelper().getQiNiuInfo()?.subscribe({ authTokenResponse ->
                    SBApplication.uploadManager.put(filePath, "android" + Date().time + ".jpg", authTokenResponse.authToken, { key, info, res ->
                        //res 包含 hash、key 等信息，具体字段取决于上传策略的设置
                        if (info.isOK) {

                            hideLoadingDialog()
                            viewModel.babyIcon.value = authTokenResponse.domain + key
                            viewModel.canClick()

                        } else {
                            hideLoadingDialog()
                        }
                    }, null)

                }, { throwable ->
                    hideLoadingDialog()
                    showToast(throwable.message)
                })
            } else {
                hideLoadingDialog()
            }
        }

        dataBinding.activityLibraryTwoIcon.setOnClickListener {
            TakePhotoPopWindowUtils.takePhoto(this, dataBinding.activityLibraryTwoCl, takePhotoResult, selectPicResult)
        }


        dataBinding.activityLibraryTwoBoyLl.setOnClickListener {
            viewModel.babySex.value = viewModel.sexBoy
            viewModel.canClick()
        }
        dataBinding.activityLibraryTwoGirlLl.setOnClickListener {
            viewModel.babySex.value = viewModel.sexGirl
            viewModel.canClick()
        }

        dataBinding.activityLibraryTwoJump.setOnClickListener {
            val identityType = intent.getIntExtra(KeyString.identityType, 0)
            val userIdentity = intent.getStringExtra(KeyString.userIdentity)!!
            val request = CreateFamilyRequest(identityType, userIdentity, "", 0, 0, "", "", "", "CM", "KG")
            HttpHelper().createFamily(request)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({ i ->
                HttpHelper().getDefaultFamily()?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
                    hideLoadingDialog()
                    SBApplication.userData = it
                    SBApplication.hasWeightMachine = false
                    SBApplication.hasHeightMachine = false
                    SBApplication.hasToothBrushMachine = false
                    it.deviceList?.forEach { d ->
                        if (d.deviceType == 1) {
                            SBApplication.hasWeightMachine = true
                        } else if (d.deviceType == 2) {
                            SBApplication.hasHeightMachine = true
                        } else if (d.deviceType == 3) {
                            SBApplication.hasToothBrushMachine = true
                        }
                    }

                    PushManager.getInstance().bindAlias(this, SBApplication.userData.userAlias)
                    async {
                        DataStoreUtils.writeStringToDataStore(KeyString.userAlias, SBApplication.userData.userAlias)
                    }

                    ARouter.getInstance().build(MAIN_ROUTER).navigation()
                    setResult(1024)
                    finish()
                }, {
                    hideLoadingDialog()
                    showToast(it.message)
                })
            }, {
                hideLoadingDialog()
                showToast(it.message)
            })
        }
    }
}